
import caller
import webpage
import json

def getRecPage(recover):
    cr = caller.RecoveryCaller(recover)
    page = webpage.WebPage(cr.pageref, cr)
    return page

class WebKit:
    def __init__(self, group, isStatic = False):
        self.group = group
        self.isStatic = isStatic
        self.cr = caller.Caller(group, isStatic)
        self.filterRules = []

    def release(self):
        self.cr.close()

    def setFilterRules(self, rules):
        self.filterRules = rules
        
    def isFailed(self):
        return self.cr.isFailed()

    def getWebPage(self, url, level = 100, timeMS = 0, destroyTimeMS = None):
        if url == "":
            url = "about:blank"

        #jsonstr = json.dumps(self.filterRules)
        args = [0, url, [], level, timeMS]
        if destroyTimeMS != None:
            args.append(destroyTimeMS)

        times = 10;
        while not times == 0:
            retmessage = self.cr.call(0, caller.Function.WEBKIT_LONG_GET_LONG_REF_STRING_URL, args, timeMS + 60000)
            retobj = self.cr.getReturnObjValue(retmessage)
            if self.isFailed() or retobj == None:
                self.cr.close()
                self.cr = caller.Caller(self.group, self.isStatic)
                times -= 1
            elif retobj['error'] != -2 or retobj['error'] != -5:
                break;
            else: 
                self.cr = caller.Caller(self.group, self.isStatic)
                times -= 1

        if self.isFailed() or retobj == None:
            return None

        if retobj['error'] < 0:
            return None
        
        if retobj['page'] <= 0:
            return None

        pageref = retobj['page']
        page = webpage.WebPage(pageref, self.cr, self.filterRules)
        return page

    def getWebPageWithCookies(self, url, cookies, level = 100, timeMS = 0, destroyTimeMS = None):
        if url == "":
            url = "about:blank"

        args = [0, url, cookies, level, timeMS]
        if destroyTimeMS != None:
            args.append(destroyTimeMS)

        times = 10;
        while not times == 0:
            retmessage = self.cr.call(0, caller.Function.WEBKIT_LONG_GET_LONG_REF_STRING_URL, args, timeMS + 60000)
            retobj = self.cr.getReturnObjValue(retmessage)
            if self.isFailed() or retobj == None:
                self.cr.close()
                self.cr = caller.Caller(self.group, self.isStatic)
                times -= 1
            elif retobj['error'] != -2 or retobj['error'] != -5:
                break;
            else: 
                self.cr = caller.Caller(self.group, self.isStatic)
                times -= 1

        if self.isFailed() or retobj == None:
            return None

        if retobj['error'] < 0:
            return None
        
        if retobj['page'] <= 0:
            return None

        pageref = retobj['page']
        page = webpage.WebPage(pageref, self.cr, self.filterRules)
        return page



